package alkaid.eis.sys.entity;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedAttributeNode;
import javax.persistence.NamedEntityGraph;
import javax.persistence.NamedEntityGraphs;
import javax.persistence.OneToMany;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;

import org.springframework.beans.BeanUtils;

import alkaid.eis.sys.core.AbstractBaseEntity;
import lombok.Getter;
import lombok.Setter;

/**
 * 部门
 * 
 * @author Lucky Yang
 * @since 0.0.1
 */
@Entity
@Getter
@Setter
@Table(name = "eis_sys_dept")
@NamedEntityGraphs({
        @NamedEntityGraph(name = "Dept.children", attributeNodes = {
                @NamedAttributeNode("children")
        })
})
public class Dept extends AbstractBaseEntity {
    public final static String PATH_SEP = "/";
    /**
     * 上级部门
     */
    @ManyToOne
    @JoinColumn(name = "pid")
    private Dept parent;

    /**
     * 名称
     */
    @Column(nullable = false)
    private String name;

    /**
     * 启用
     */
    private Boolean enabled;

    /**
     * 排序
     */
    private Integer orderNo;

    /**
     * 子部门个数
     */
    private Integer childCount = 0;

    /**
     * id路径
     */
    private String pathId;

    /**
     * 子部门
     */
    @OneToMany(mappedBy = "parent", cascade = { CascadeType.PERSIST})
    private List<Dept> children  = new ArrayList<>();

    
    public Dept() {
    }

    public Dept(String name) {
        this.name = name;
    }

    public Dept(Dept parent, String name, Boolean enabled, Integer orderNo) {
        this.parent = parent;
        this.name = name;
        this.enabled = enabled;
        this.orderNo = orderNo;
    }

    @PrePersist
    @PreUpdate
    public void prePersist() {
        if (parent != null) {
            pathId = parent.getPathId() + PATH_SEP + getId();
        } else {
            pathId = getId().toString();
        } 
    }

    public void copy(Dept source) {
        BeanUtils.copyProperties(source, this, "id,parent,pathId,childCount,children".split(","));
    }

}
